<script setup lang="ts">
import { Popup } from "vant";
import { ref, watch, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { Field } from "vant";
import { WalletAxios } from "@/api";
import sortBy from "lodash";
import PubSub from "pubsub-js";
import { PubSubEnum } from "@/types";
import { UserStore } from "@/store";
const userStore = UserStore();
const { t } = useI18n();

interface getbankData {
  id: number;
  isSuccess: number;
  receivingAccount: string;
}

const props = defineProps<{
  title: string;
  momey: number;
  bankData: getbankData;
  isdisabled: boolean;
  paymentChannelType: number;
  withdrawalMethod: any;
}>();
onMounted(async () => {
  await getExtractInfo(props.withdrawalMethod[0]);
});
const popupShow = ref(false);
//打开提现弹窗
const clickPopup = () => {
  // submitButtonType.value = props.bankData.receivingAccount.length === 11 ? true : false;
  popupShow.value = true;
};
// const selectList = reactive([
//   { name: t("withdrawals.cpf"), value: "CPF" },
//   { name: t("withdrawals.email"), value: "EMAIL" },
//   { name: t("withdrawals.phone"), value: "PHONE" },
//   { name: t("withdrawals.cnpj"), value: "CNPJ" },
// ]);
const selectType = ref(0);
const paymentMethod = ref("CPF");
const selectTypeFun = (index, item) => {
  selectType.value = index;
  paymentMethod.value = item;
  getExtractInfo(paymentMethod.value);
};
//查询获取绑定的银行卡receivingAccount有值且isSuccess==0可以修改，isSuccess==1不能修改
const banksItem = ref({
  id: 0,
  receivingAccount: "",
  isSuccess: 0, //是否绑定成功,该银行卡是否提现成功过，0：未成功，1：成功(如果是该状态，则不能再编辑)
});
const getExtractInfo = async paymentMethod => {
  await WalletAxios.getUserBankCardByUid({ paymentMethod: paymentMethod }).then(res => {
    banksItem.value = Object.assign(banksItem, res);
    validationRulesFun(paymentMethod);
    if (paymentMethod === "CPF") {
      openingBank.value = banksItem.value.receivingAccount;
      cpfIdLoad.value = true;
    }
    if (paymentMethod === "EMAIL") {
      emailVal.value = banksItem.value.receivingAccount;
      emailLoad.value = true;
    }
    if (paymentMethod === "PHONE") {
      phoneVal.value = banksItem.value.receivingAccount;
      phoneload.value = true;
    }
    if (paymentMethod === "CNPJ") {
      cnpjIdVal.value = banksItem.value.receivingAccount;
      cnpjIdLoad.value = true;
    }
    if (paymentMethod === "EVP") {
      evpVal.value = banksItem.value.receivingAccount;
      evpValLoad.value = true;
    }
    banksItem.value.isSuccess = res.isSuccess;
  });
};
//evp
const evpVal = ref("");
const evpValBlur = ref(false);
const evpValLoad = ref(false);
const evpValBlurFun = () => {
  evpValBlur.value = false;
};
const evpValFocusFun = () => {
  evpValBlur.value = true;
};
const isEvpVal = evpVal => {
  const evpValRegex = /^[0-9 a-z]{8}-[0-9 a-z]{4}-[0-9 a-z]{4}-[0-9 a-z]{4}-[0-9 a-z]{12}$/;
  return evpValRegex.test(evpVal);
};
//cpfID
const openingBank = ref("");
const cpfIdBlur = ref(false);
const cpfIdLoad = ref(false);
const cpfIdBlurFun = () => {
  cpfIdBlur.value = false;
};
const cpfIdFocusFun = () => {
  cpfIdBlur.value = true;
};
// 邮箱
const emailVal = ref("");
const emailBlur = ref(false);
const emailLoad = ref(false);
const emailBlurFun = () => {
  emailBlur.value = false;
};
const emailFocusFun = () => {
  emailBlur.value = true;
};
const isValidEmail = email => {
  const emailRegex = /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(email);
};
//手机
const phoneVal = ref("");
const phoneload = ref(false);
const phoneBlur = ref(false);
const phoneBlurFun = () => {
  phoneBlur.value = false;
};
const phoneFocusFun = () => {
  phoneBlur.value = true;
};
//cnpjId
const cnpjIdVal = ref("");
const cnpjIdBlur = ref(false);
const cnpjIdLoad = ref(false);
const cnpjIdBlurFun = () => {
  cnpjIdBlur.value = false;
};
const cnpjIdFocusFun = () => {
  cnpjIdBlur.value = true;
};
//提现人的名称
const openingName = ref(userStore.userInfoDetails.profile.cpfName);
const openingNameBlur = ref(false);
const openingNameBlurFun = () => {
  openingNameBlur.value = false;
};
const openingNameFocusFun = () => {
  openingNameBlur.value = true;
};
//cpf号码
const receivingAccount = ref(userStore.userInfoDetails.profile.cpf);
const cpfBlur = ref(false);
const cpfBlurFun = () => {
  cpfBlur.value = false;
};
const cpfFocusFun = () => {
  cpfBlur.value = true;
};
const submitButtonType = ref(false);
const receivingVal = ref("");
watch(
  [
    () => openingBank.value,
    () => openingName.value,
    () => receivingAccount.value,
    () => emailVal.value,
    () => phoneVal.value,
    () => cnpjIdVal.value,
    () => evpVal.value,
  ],
  () => {
    validationRulesFun(paymentMethod.value);
  },
);
//验证规则
const validationRulesFun = paymentName => {
  if (paymentName === "CPF") {
    submitButtonType.value =
      openingBank.value.length === 11 && openingName.value !== "" && receivingAccount.value !== ""
        ? true
        : false;
    receivingVal.value = openingBank.value;
  }
  if (paymentName === "PHONE") {
    submitButtonType.value =
      phoneVal.value.length == 11 && openingName.value !== "" && receivingAccount.value !== ""
        ? true
        : false;
    receivingVal.value = phoneVal.value;
  }
  if (paymentName === "CNPJ") {
    submitButtonType.value =
      cnpjIdVal.value.length === 14 && openingName.value !== "" && receivingAccount.value !== ""
        ? true
        : false;
    receivingVal.value = cnpjIdVal.value;
  }
  if (paymentName === "EMAIL") {
    submitButtonType.value =
      isValidEmail(emailVal.value) && openingName.value !== "" && receivingAccount.value !== ""
        ? true
        : false;
    receivingVal.value = emailVal.value;
  }
  if (paymentName === "EVP") {
    submitButtonType.value =
      isEvpVal(evpVal.value) && openingName.value !== "" && receivingAccount.value !== ""
        ? true
        : false;
    receivingVal.value = evpVal.value;
  }
};
//绑定提现方式
const submitExtract = sortBy.throttle(() => {
  console.log(banksItem.value.isSuccess, "绑定提现方式为什么", banksItem.value.receivingAccount);
  //这里是编辑提现账户
  if (banksItem.value.isSuccess === 0 && banksItem.value.receivingAccount !== "") {
    WalletAxios.updateUserBankCard({
      receivingAccount: receivingVal.value,
      paymentMethod: paymentMethod.value,
    }).then(_item => {
      WalletAxios.createWithdrawalPaymentOrder({
        currencyAmount: ensureTwoDecimalPlaces(props.momey),
        paymentChannelType: props.paymentChannelType,
        paymentMethod: paymentMethod.value,
      }).then(res => {
        const code = res.code;
        if (res.code === 0) {
          emits("onFinish");
          PubSub.publish(PubSubEnum.SHOW_SUCCESS_TIP);
          popupShow.value = false;
        } else if (code === 2007) {
          PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
            text: "用户打码量不为0，不让提现",
          });
        } else if (code === 2008) {
          PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
            text: "提现金额小于最小值，不让提现",
          });
        } else if (code === 2009) {
          PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
            text: "提现金额大于最大值，不让提现",
          });
        } else if (code === 2010) {
          PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
            text: "充值金额小于最小值，不让提现",
          });
        }
      });
    });
  } else if (banksItem.value.isSuccess === 0 && banksItem.value.receivingAccount === "") {
    //这里是添加提现账户的
    WalletAxios.userBindBankCard({
      receivingAccount: receivingVal.value,
      paymentMethod: paymentMethod.value,
    }).then(_item => {
      getExtractInfo(paymentMethod.value);
      WalletAxios.createWithdrawalPaymentOrder({
        currencyAmount: ensureTwoDecimalPlaces(props.momey),
        paymentChannelType: props.paymentChannelType,
        paymentMethod: paymentMethod.value,
      }).then(res => {
        const code = res.code;
        if (res.code === 0) {
          emits("onFinish");
          PubSub.publish(PubSubEnum.SHOW_SUCCESS_TIP);
          popupShow.value = false;
        } else if (code === 2007) {
          PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
            text: "用户打码量不为0，不让提现",
          });
        } else if (code === 2008) {
          PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
            text: "提现金额小于最小值，不让提现",
          });
        } else if (code === 2009) {
          PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
            text: "提现金额大于最大值，不让提现",
          });
        } else if (code === 2010) {
          PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
            text: "充值金额小于最小值，不让提现",
          });
        }
      });
    });
  } else {
    WalletAxios.fxPayWithdraw({ fxfee: props.momey }).then(res => {
      // emits("onFinish");
      // PubSub.publish(PubSubEnum.SHOW_SUCCESS_TIP);
      // popupShow.value = false;
      const code = res.code;
      if (res.code === 0) {
        emits("onFinish");
        PubSub.publish(PubSubEnum.SHOW_SUCCESS_TIP);
        popupShow.value = false;
      } else if (code === 2007) {
        PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
          text: "用户打码量不为0，不让提现",
        });
      } else if (code === 2008) {
        PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
          text: "提现金额小于最小值，不让提现",
        });
      } else if (code === 2009) {
        PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
          text: "提现金额大于最大值，不让提现",
        });
      } else if (code === 2010) {
        PubSub.publish(PubSubEnum.SHOW_ERROR_TIP, {
          text: "充值金额小于最小值，不让提现",
        });
      }
    });
  }
}, 1000);
defineExpose({ clickPopup });
const emits = defineEmits(["onFinish"]);
//转化小数位
function ensureTwoDecimalPlaces(num) {
  // 将数字转换为字符串
  let numStr = num.toString();

  // 检查是否有小数点
  if (numStr.includes(".")) {
    // 获取小数部分的长度
    const decimalPart = numStr.split(".")[1];
    const decimalLength = decimalPart.length;

    // 如果小数部分长度小于2，则补足两位
    if (decimalLength < 2) {
      return parseFloat(numStr + "0".repeat(2 - decimalLength)).toFixed(2);
    } else {
      // 如果已经有两位或更多小数位，直接返回
      return numStr;
    }
  } else {
    // 如果没有小数部分，直接补足两位
    return parseFloat(numStr + ".00").toFixed(2);
  }
}
</script>
<template>
  <!-- 充值的 -->
  <Popup
    v-model:show="popupShow"
    :position="'bottom'"
    z-index="1000"
    duration="0.5"
    style="height: 100%; background-color: #1b0a24 !important"
    :overlay="false"
    :safe-area-inset-top="true"
    :safe-area-inset-bottom="true"
  >
    <div class="content-frame">
      <div class="title-frame df jc-center ai-center">
        <img
          class="close-img"
          src="@/image/new_img/home/user_img/huitui_bai.png"
          @click="popupShow = false"
        />
        <div class="title-name df ai-center">{{ props.title }}</div>
      </div>
      <div class="content-info-frame">
        <div class="money-content-frame">
          <div class="title-frame2">
            {{ t("paymentPage.myBalance") }}
          </div>
          <div class="money-frame df ai-center jc-center">
            <img class="pdd_icon" src="@/image/new_img/home/user_img/pdd_icon_coin.png" />
            <div class="money-val">{{ props.momey }}</div>
          </div>
        </div>
        <div class="select-frame">
          <div class="select-title-frame df ai-center">{{ t("withdrawals.taxType") }}</div>
          <div class="select-content-frame df">
            <div
              v-for="(item, index) in props.withdrawalMethod"
              :key="index"
              class="select-content df ai-center jc-center test-spacing"
              :class="{ 'dinfe-type': selectType == index }"
              @click="selectTypeFun(index, item)"
            >
              {{ item }}
            </div>
          </div>
        </div>
        <!-- CPF ID -->
        <div v-show="paymentMethod == 'CPF'" class="input-content-frame">
          <div class="input-title-content marginTop">{{ t("withdrawals.cpfId") }}</div>
          <div
            class="input-frame df ai-center"
            :class="{
              'field-val': openingBank.length !== 11 && cpfIdLoad,
              'field-val-true': openingBank.length === 11 && cpfIdBlur,
            }"
          >
            <Field
              v-if="banksItem.isSuccess == 0 || banksItem.receivingAccount === ''"
              v-model="openingBank"
              class="field--frame"
              type="number"
              :center="true"
              :placeholder="t('inputPlaceholder.cpfIdInput')"
              color="#ffffff"
              :disabled="banksItem.isSuccess === 1 ? true : false"
              @blur="cpfIdBlurFun"
              @focus="cpfIdFocusFun"
            />
            <div v-else class="disabled-frame df ai-center">
              {{ banksItem.receivingAccount }}
            </div>
          </div>
          <div v-show="openingBank.length !== 11 && cpfIdLoad" class="cpfVerificar-frame">
            {{ t("inputError.cpfVerificar") }}
          </div>
        </div>
        <!-- EVP-->
        <div v-show="paymentMethod == 'EVP'" class="input-content-frame">
          <div class="input-title-content marginTop">{{ t("withdrawals.evpId") }}</div>
          <div
            class="input-frame df ai-center"
            :class="{
              'field-val': !isEvpVal(evpVal) && evpValLoad,
              'field-val-true': isEvpVal(evpVal) && evpValBlur,
            }"
          >
            <Field
              v-if="banksItem.isSuccess == 0 || banksItem.receivingAccount === ''"
              v-model="evpVal"
              class="field--frame"
              :center="true"
              :placeholder="t('inputPlaceholder.evpInput')"
              color="#ffffff"
              :disabled="banksItem.isSuccess === 1 ? true : false"
              @blur="evpValBlurFun"
              @focus="evpValFocusFun"
            />
            <div v-else class="disabled-frame df ai-center">
              {{ banksItem.receivingAccount }}
            </div>
          </div>
          <div v-show="!isEvpVal(evpVal) && evpValLoad" class="cpfVerificar-frame">
            {{ t("inputError.evpVerificar") }}
          </div>
        </div>
        <!-- Email -->
        <div v-show="paymentMethod == 'EMAIL'" class="input-content-frame">
          <div class="input-title-content">{{ t("withdrawals.email") }}</div>
          <div
            class="input-frame df ai-center"
            :class="{
              'field-val': !isValidEmail(emailVal) && emailLoad,
              'field-val-true': emailBlur && isValidEmail(emailVal),
            }"
          >
            <Field
              v-model="emailVal"
              class="field--frame"
              :center="true"
              :placeholder="t('inputPlaceholder.emailInput')"
              color="#ffffff"
              @blur="emailBlurFun"
              @focus="emailFocusFun"
            />
          </div>
          <div v-show="!isValidEmail(emailVal) && emailLoad" class="cpfVerificar-frame">
            {{ t("inputError.emailExtract") }}
          </div>
        </div>
        <!-- PHONE -->
        <div v-show="paymentMethod == 'PHONE'" class="input-content-frame">
          <div class="input-title-content">{{ t("withdrawals.phoneId") }}</div>
          <div
            class="input-frame df ai-center"
            :class="{
              'field-val': phoneVal.length !== 11 && phoneload,
              'field-val-true': phoneVal.length == 11 && phoneVal !== '' && phoneBlur,
            }"
          >
            <Field
              v-model="phoneVal"
              class="field--frame"
              type="number"
              :center="true"
              :placeholder="t('inputPlaceholder.phoneInput')"
              color="#ffffff"
              @blur="phoneBlurFun"
              @focus="phoneFocusFun"
            />
          </div>
          <div v-show="phoneVal.length !== 11 && phoneload" class="cpfVerificar-frame">
            {{ t("inputError.phoneVerificar") }}
          </div>
        </div>
        <!-- CNPJID -->
        <div v-show="paymentMethod == 'CNPJ'" class="input-content-frame">
          <div class="input-title-content">{{ t("withdrawals.cnpjId") }}</div>
          <div
            class="input-frame df ai-center"
            :class="{
              'field-val': cnpjIdVal.length !== 14 && cnpjIdLoad,
              'field-val-true': cnpjIdVal.length === 14 && cnpjIdBlur,
            }"
          >
            <Field
              v-model="cnpjIdVal"
              class="field--frame"
              type="number"
              :center="true"
              :placeholder="t('inputPlaceholder.cnpjInput')"
              color="#ffffff"
              @blur="cnpjIdBlurFun"
              @focus="cnpjIdFocusFun"
            />
          </div>
          <div v-show="cnpjIdVal.length !== 14 && cnpjIdLoad" class="cpfVerificar-frame">
            {{ t("inputError.cnpjVerificar") }}
          </div>
        </div>
        <!-- 提现人的名字和cpf -->
        <div class="input-content-frame">
          <div class="input-title-content">{{ t("withdrawals.other") }}</div>
          <div
            class="input-frame df ai-center"
            :class="{ 'field-val-true': openingName !== '' && openingNameBlur }"
          >
            <Field
              v-if="openingName === ''"
              v-model="openingName"
              class="field--frame"
              :center="true"
              :placeholder="t('inputPlaceholder.otherInput')"
              color="#ffffff"
              @blur="openingNameBlurFun"
              @focus="openingNameFocusFun"
            />
            <div v-else class="disabled-frame df ai-center">
              {{ openingName }}
            </div>
          </div>
        </div>
        <div class="input-content-frame">
          <div class="input-title-content">{{ t("withdrawals.cpf") }}</div>
          <div
            class="input-frame df ai-center"
            :class="{
              'field-val': receivingAccount !== '' && receivingAccount.length !== 11,
            }"
          >
            <Field
              v-if="receivingAccount === ''"
              v-model="receivingAccount"
              class="field--frame"
              type="number"
              :center="true"
              :placeholder="t('inputPlaceholder.cpfIdInput')"
              color="#ffffff"
              @blur="cpfBlurFun"
              @focus="cpfFocusFun"
            />
            <div v-else class="disabled-frame df ai-center">
              {{ receivingAccount }}
            </div>
          </div>
          <div
            v-show="receivingAccount !== '' && receivingAccount.length !== 11"
            class="cpfVerificar-frame"
          >
            {{ t("inputError.cpfVerificar") }}
          </div>
        </div>
        <div class="bottom-frame">
          <img
            v-show="!submitButtonType"
            src="@/image/new_img/home/user_img/btnv2_refund_disable.png"
          />
          <img
            v-show="submitButtonType"
            src="@/image/new_img/home/user_img/btnv2_exit.png"
            @click="submitExtract"
          />
        </div>
        <div class="withdrawalInstructions">
          {{ t("withdrawals.withdrawalInstructions") }}
        </div>
      </div>
    </div>
  </Popup>
</template>
<style lang="less" scoped>
.content-frame {
  width: 100%;
  height: 100%;
  overflow-y: hidden;
  /*半透明背景色 */
  // backdrop-filter: blur(20px);
  /*背景模糊效果 */
  // -webkit-backdrop-filter: blur(20px);

  .title-frame {
    width: 100%;
    height: 105px;
    background: #1b0a24 !important;
    position: relative;
    left: 0;
    right: 0;
  }

  .close-img {
    width: 42px;
    height: 42px;
    padding: 20px;
    border-radius: 50%;
    background-color: #ffffff14;
    margin-left: 30px;
    position: absolute;
    left: 0;
    top: 14.5px;
  }
}
.title-name {
  font-size: 32px;
  color: #ffffff;
}
.content-info-frame {
  width: 100%;
  height: calc(100% - 105px);
  overflow-y: scroll;
}
.content-info-frame::-webkit-scrollbar {
  display: none;
  overflow: -moz-scrollbars-none; /* Firefox */
  -ms-overflow-style: none; /* IE 和 Edge */
}
.money-content-frame {
  .title-frame2 {
    width: 100%;
    height: auto;
    text-align: center;
    font-size: 28px;
    color: rgba(255, 255, 255, 0.65);
    margin-top: 39px;
  }
  .money-content-frame::-webkit-scrollbar {
    display: none;
    overflow: -moz-scrollbars-none; /* Firefox */
    -ms-overflow-style: none; /* IE 和 Edge */
  }
  .money-frame {
    width: auto;
    height: auto;
    margin-top: 32px;

    .pdd_icon {
      width: 48px;
      height: 48px;
      margin-right: 15px;
    }

    .money-val {
      color: #ffffff;
      font-size: 75px;
      font-weight: 700;
    }
  }
}

.select-frame {
  margin-top: 58px;
  width: calc(100% - 105px);
  height: auto;
  margin-left: 30px;

  .select-title-frame {
    height: 44px;
    font-size: 28px;
    color: rgba(255, 255, 255, 0.85);
  }

  .select-content {
    flex: 1;
    height: 79px;
    font-size: 26px;
    color: rgba(255, 255, 255, 0.45);
    border-bottom: 1px solid rgba(255, 255, 255, 0.15);
  }

  .dinfe-type {
    color: #ab3fe7;
    border-bottom: 1px solid #ab3fe7;
  }

  .select-content-frame {
    width: calc(100% - 20px);
  }
}

.input-content-frame {
  width: calc(100% - 60px);
  margin: auto;

  .input-frame {
    width: 90%;
    height: 100px;
    border: 1px solid rgba(255, 255, 255, 0.04);
    background-color: rgba(255, 255, 255, 0.04);
    border-radius: 28px;
    margin-top: 10px;
    padding-left: 20px;
  }

  .input-title-content {
    font-weight: 400;
    font-size: 28px;
    color: #ffffff;
    margin-top: 34px;
  }
  .marginTop {
    margin-top: 44px;
  }
  .field--frame {
    // height: 80px;
  }

  .cpfVerificar-frame {
    font-size: 28px;
    color: #eb5757;
    margin-top: 13px;
  }

  .field-val {
    border-color: #eb5757;
  }

  .field-val-true {
    border-color: #ab3fe7;
  }
}

:deep(.input-frame) {
  .van-field__control {
    height: 60px;
  }

  input {
    font-size: 24px;
    color: #ffffff;
  }

  input::placeholder {
    font-size: 24px;
    color: #757575;
  }
}

.bottom-frame {
  margin-top: 61px;
  text-align: center;

  img {
    width: 249px;
    height: 100px;
  }
}

.withdrawalInstructions {
  width: 520px;
  height: 40px;
  line-height: 20px;
  font-size: 21.504px;
  color: rgba(255, 255, 255, 0.3);
  text-align: center;
  margin: auto;
  margin-top: 79px;
  margin-bottom: 60px;
}

.disabled-frame {
  font-size: 24px;
  color: #ffffff;
  margin-left: 15px;
}
:deep(.field--frame) {
  input::placeholder {
    font-size: 26px;
  }
}
</style>
